import axios from 'axios'
import router from '../router/index'

export default {
  install (Vue, options) {
    const HTTP_POST = 'post'
    const HTTP_GET = 'get'
    const HTTP_DELETE = 'delete'
    const HTTP_PUT = 'put'
    Vue.prototype.httpAction = function (url, requestType, params, callback) {
      if (requestType === HTTP_POST) {
        axios.post(url, {
          params: params
        })
          .then(response => function () {
            callback(response)
          })
      } else if (requestType === HTTP_GET) {
        axios.get(url, {
          params: params
        })
          .then(response => function () {
            console.log('httpAction:%o', response)
            callback(response)
          }).catch(error => {
            console.log('on error:%o', error)
          })
      } else if (requestType === HTTP_DELETE) {
        axios.get(url, {
          params: params
        })
          .then(response => function () {
            callback(response)
          })
      } else if (requestType === HTTP_PUT) {
        axios.get(url, {
          params: params
        })
          .then(response => function () {
            callback(response)
          })
      }
    }
    // check token status
    Vue.prototype.checkToken = function (tokenKey, loginTimeKey, usernameKey) {
      let token = localStorage.getItem(tokenKey)
      let loginTime = localStorage.getItem(loginTimeKey)
      let host = localStorage.getItem('host')
      if (host !== getGServerUrl()) {
        loginTime = 0
      }
      if (token === null) {
        router.push({path: '/login'})
      }
      let currentTime = new Date().getTime()
      if (currentTime - loginTime > GTokenExpireTime) {
        localStorage.removeItem(tokenKey)
        localStorage.removeItem(loginTimeKey)
        localStorage.removeItem(usernameKey)
        router.push({path: '/login'})
      }
    }
  }
}
